#!/bin/bash

case $1 in
  config)
    cat <<'EOM'
multigraph https_dns_proxy_count
graph_title HTTPS DNS proxy - count
graph_vlabel count
graph_category network
graph_scale no
graph_args --base 1000 --lower-limit 0
requests.label Requests
responses.label Responses
tcprequests.label TcpRequests
tcpresponses.label TcpResponses

multigraph https_dns_proxy_latency
graph_title HTTPS DNS proxy - latency
graph_vlabel latency
graph_category network
graph_scale no
graph_args --base 1000 --lower-limit 0
latency.label Latency
tcplatency.label TcpLatency

multigraph https_dns_proxy_connections
graph_title HTTPS DNS proxy - connections
graph_vlabel count
graph_category network
graph_scale no
graph_args --base 1000 --lower-limit 0
opened.label Opened
closed.label Closed
reused.label Reused
EOM
    exit 0;;

  autoconf)
    pgrep https_dns_proxy >/dev/null 2>&1 \
      && echo "yes" \
      || echo "no"
    exit 0;;
esac

log_lines=$(journalctl --unit https_dns_proxy.service --output cat --since '6 minutes ago')
pattern='stat\.c:[0-9]+ ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)$'

# match log lines with pattern (last match will be used)
IFS='
'
for line in $log_lines; do
  if [[ $line =~ $pattern ]]; then
    stat=("${BASH_REMATCH[@]}")
  # else
  #   echo "stat regexp did not match with line: $line" >&2
  fi
done

if [ -n "${stat[3]}" ] && \
   [ -n "${stat[2]}" ] && \
   [ "${stat[2]}" -gt "0" ]; then
  latency=$((${stat[3]} / ${stat[2]}))
fi

if [ -n "${stat[11]}" ] && \
   [ -n "${stat[10]}" ] && \
   [ "${stat[10]}" -gt "0" ]; then
  tcplatency=$((${stat[11]} / ${stat[10]}))
fi

echo "multigraph https_dns_proxy_count"
echo "requests.value ${stat[1]:-U}"
echo "responses.value ${stat[2]:-U}"
echo "tcprequests.value ${stat[9]:-U}"
echo "tcpresponses.value ${stat[10]:-U}"
echo "multigraph https_dns_proxy_latency"
echo "latency.value ${latency:-0}"
echo "tcplatency.value ${tcplatency:-0}"
echo "multigraph https_dns_proxy_connections"
echo "opened.value ${stat[6]:-U}"
echo "closed.value ${stat[7]:-U}"
echo "reused.value ${stat[8]:-U}"
